package cn.tedu.mall.order.controller;

import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.JsonResult;
import cn.tedu.mall.order.service.IOmsCartService;
import cn.tedu.mall.pojo.order.dto.CartAddDTO;
import cn.tedu.mall.pojo.order.dto.CartUpdateDTO;
import cn.tedu.mall.pojo.order.vo.CartStandardVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.spring.web.json.Json;

import java.util.List;

@RestController
@RequestMapping("/oms/cart")
@Api(tags = "购物车模块")
public class OmsCartController {
    @Autowired
    private IOmsCartService omsCartService;

    @PostMapping("/add")
    @ApiOperation("新增商品到购物车")
    //需要校验是否有执行权限
    @PreAuthorize("hasRole('user')")
    //@Validated校验CartAddDTO信息是否完整，验证不通过，会由统一的BindException处理
    public JsonResult addCart(@Validated CartAddDTO cartAddDTO){
        omsCartService.addCart(cartAddDTO);
        return JsonResult.ok("新增商品到购物车成功");
    }

    @GetMapping("/list")
    @ApiOperation("分页查询购物车")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页码",name = "page",dataType = "int",example = "1"),
            @ApiImplicitParam(value = "每页条数",name = "pageSize",dataType = "int",example = "10")
    })
    @PreAuthorize("hasAuthority('ROLE_user')")
    public JsonResult<JsonPage<CartStandardVO>> getCartsByPage(Integer page, Integer pageSize){
        JsonPage<CartStandardVO> jsonPage = omsCartService.listCarts(page, pageSize);
        return JsonResult.ok(jsonPage);
    }

    @PostMapping("/update")
    @ApiOperation("修改购物车中的数量")
    @PreAuthorize("hasRole('user')")
    public JsonResult updateCartQuantity(@Validated CartUpdateDTO cartUpdateDTO){
        omsCartService.updateQuantity(cartUpdateDTO);
        return JsonResult.ok("修改成功");
    }

    @PostMapping("/delete")
    @ApiOperation("根据选中的商品进行删除")
    @ApiImplicitParam(value = "id数组",name = "ids",required = true,dataType = "array")
    @PreAuthorize("hasRole('user')")
    public JsonResult  deleteCartsByIds(Long[] ids){
        omsCartService.removeCart(ids);
        return JsonResult.ok("商品删除成功");
    }
    @PostMapping("/delete/all")
    @ApiOperation("清空当前用户的购物车")
    @PreAuthorize("hasRole('user')")
    public JsonResult  deleteCartsByUserId(){
        omsCartService.removeAllCarts();
        return JsonResult.ok("购物车清空成功");
    }
}
